import Cookies from 'js-cookie'

const state = {
    sidebar: {
        opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
        withoutAnimation: false
    },
    device: 'desktop',
    isLoading: true,
    visitedViews: []
}

const mutations = {
    TOGGLE_SIDEBAR: state => {
        state.sidebar.opened = !state.sidebar.opened
        state.sidebar.withoutAnimation = false
        if (state.sidebar.opened) {
            Cookies.set('sidebarStatus', 1)
        } else {
            Cookies.set('sidebarStatus', 0)
        }
    },
    CLOSE_SIDEBAR: (state, withoutAnimation) => {
        Cookies.set('sidebarStatus', 0)
        state.sidebar.opened = false
        state.sidebar.withoutAnimation = withoutAnimation
    },
    TOGGLE_DEVICE: (state, device) => {
        state.device = device
    },
    TOGGLE_LOADINGSHOW: (state, isLoading) => {
        state.isLoading = isLoading
    },
    ADD_VISITED_VIEW: (state, visitedViews) => {
        state.visitedViews = visitedViews
            // if (state.visitedViews.some(v => v.path === view.path)) return
            // state.visitedViews.push(
            //     Object.assign({}, view, {
            //         title: view.meta.title || 'no-name'
            //     })
            // )
    },
    DEL_VISITED_VIEW: (state, view) => {
        for (const [i, v] of state.visitedViews.entries()) {
            if (v.path === view.path) {
                state.visitedViews.splice(i, 1)
                break
            }
        }
    },
    CLOSE_OTHERS_TAGS: (state, index) => {
        state.visitedViews.splice(index, 1)
    },
    DEL_ALL_VISITED_VIEWS: state => {
        const affixTags = state.visitedViews.filter(tag => tag.meta.affix)
        state.visitedViews = affixTags
    }

}

const actions = {
    toggleSideBar({ commit }) {
        commit('TOGGLE_SIDEBAR')
    },
    closeSideBar({ commit }, { withoutAnimation }) {
        commit('CLOSE_SIDEBAR', withoutAnimation)
    },
    toggleDevice({ commit }, device) {
        commit('TOGGLE_DEVICE', device)
    },
    addView({ commit }, view) {
        commit('ADD_VISITED_VIEW', view)
    },
    delView({ commit, state }, view) {
        return new Promise(resolve => {
            commit('DEL_VISITED_VIEW', view)
            resolve(state.visitedViews)
        })
    },
    closeOthersTags({ commit }, index) {
        commit('CLOSE_OTHERS_TAGS', index)
    },
    delAllViews({ commit }) {
        commit('DEL_ALL_VISITED_VIEWS')
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}